import React, { FC, useState } from 'react';
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
import _ from 'lodash';
import { data, dataProps } from './config';

const BeautifulDnd: FC = () => {
  const [dataList, setDataList] = useState<dataProps[]>(data);
  const onBeforeCapture = () => {
    console.log('onBeforeCapture');
  };
  const onBeforeDragStart = () => {
    console.log('onBeforeDragStart');
  };
  const onDragStart = () => {
    console.log('onDragStart');
  };
  const onDragUpdate = () => {
    console.log('onDragUpdate');
  };
  const onDragEnd = (result: any) => {
    const sourceIndex = result.source.index; // 源位置的index
    const destinationIndex = result.destination.index; // 目标位置的index
    if (sourceIndex === destinationIndex) {
      return;
    }
    const data = _.cloneDeep(dataList);
    const draggedItem: dataProps = data.splice(sourceIndex, 1)[0];

    data.splice(destinationIndex, 0, draggedItem);
    setDataList(data);
  };

  return (
    <DragDropContext
      onBeforeCapture={onBeforeCapture}
      onBeforeDragStart={onBeforeDragStart}
      onDragStart={onDragStart}
      onDragUpdate={onDragUpdate}
      onDragEnd={onDragEnd}
    >
      <Droppable droppableId="droppable" direction="vertical">
        {(provided, snapshot) => {
          return (
            <div
              ref={provided.innerRef}
              className="droppable"
              {...provided.droppableProps}
            >
              {_.map(dataList, (item, key) => {
                return (
                  <Draggable key={item.id} draggableId={item.id} index={key}>
                    {(provided, snapshot) => {
                      return (
                        <div
                          ref={provided.innerRef}
                          {...provided.draggableProps}
                          {...provided.dragHandleProps}
                          className="draggable"
                        >
                          <div>{item.name}</div>
                        </div>
                      );
                    }}
                  </Draggable>
                );
              })}

              {provided.placeholder}
            </div>
          );
        }}
      </Droppable>
    </DragDropContext>
  );
};

export default BeautifulDnd;
